import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Link } from 'react-router-dom';
import {
  CheckSquare,
  FileText,
  Code,
  Github,
  Bot,
  Server,
  Database,
  Clock,
  Activity,
  TrendingUp,
  Loader2,
  AlertCircle,
  CheckCircle2,
  Calendar,
} from 'lucide-react';

interface SystemStats {
  totalTools: number;
  apiStatus: 'online' | 'offline' | 'checking';
  lastUpdate: string;
}

interface ToolStats {
  todoCount: number;
  todoCompleted: number;
  notesLength: number;
  githubCacheTime: string | null;
}

interface RecentActivity {
  id: string;
  tool: string;
  action: string;
  timestamp: string;
  icon: any;
  path: string;
}

export default function Dashboard() {
  const [systemStats, setSystemStats] = useState<SystemStats>({
    totalTools: 7,
    apiStatus: 'checking',
    lastUpdate: new Date().toLocaleString('zh-CN'),
  });

  const [toolStats, setToolStats] = useState<ToolStats>({
    todoCount: 0,
    todoCompleted: 0,
    notesLength: 0,
    githubCacheTime: null,
  });

  const [_recentActivities, setRecentActivities] = useState<RecentActivity[]>([]);

  // 检查 API 服务状态
  useEffect(() => {
    async function checkApiStatus() {
      try {
        const API_BASE = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5001/api';
        const response = await fetch(`${API_BASE}/health`);
        if (response.ok) {
          setSystemStats((prev) => ({ ...prev, apiStatus: 'online' }));
        } else {
          setSystemStats((prev) => ({ ...prev, apiStatus: 'offline' }));
        }
      } catch (error) {
        setSystemStats((prev) => ({ ...prev, apiStatus: 'offline' }));
      }
    }

    checkApiStatus();
    const interval = setInterval(checkApiStatus, 30000); // 每30秒检查一次
    return () => clearInterval(interval);
  }, []);

  // 加载工具统计数据
  useEffect(() => {
    // 待办事项统计
    const savedTodos = localStorage.getItem('feng-admin-todos');
    if (savedTodos) {
      try {
        const todos = JSON.parse(savedTodos);
        setToolStats((prev) => ({
          ...prev,
          todoCount: todos.length,
          todoCompleted: todos.filter((t: any) => t.completed).length,
        }));
      } catch (error) {
        console.error('Failed to load todos:', error);
      }
    }

    // 笔记统计
    const savedMarkdown = localStorage.getItem('feng-admin-markdown');
    if (savedMarkdown) {
      setToolStats((prev) => ({
        ...prev,
        notesLength: savedMarkdown.length,
      }));
    }

    // GitHub 缓存时间
    const githubCache = localStorage.getItem('github-trending-cache');
    if (githubCache) {
      try {
        const cache = JSON.parse(githubCache);
        if (cache.timestamp) {
          setToolStats((prev) => ({
            ...prev,
            githubCacheTime: new Date(cache.timestamp).toLocaleString('zh-CN'),
          }));
        }
      } catch (error) {
        console.error('Failed to load GitHub cache:', error);
      }
    }

    // 加载最近活动
    const activities = localStorage.getItem('feng-admin-activities');
    if (activities) {
      try {
        const parsed = JSON.parse(activities);
        setRecentActivities(parsed.slice(0, 5));
      } catch (error) {
        console.error('Failed to load activities:', error);
      }
    }
  }, []);

  // 获取 localStorage 使用情况
  const getStorageSize = () => {
    let total = 0;
    for (let key in localStorage) {
      if (localStorage.hasOwnProperty(key)) {
        total += localStorage[key].length + key.length;
      }
    }
    return (total / 1024).toFixed(2); // KB
  };

  const quickAccessTools = [
    { name: '待办事项', icon: CheckSquare, path: '/app/todo', color: 'text-blue-500' },
    { name: 'Markdown笔记', icon: FileText, path: '/app/notes', color: 'text-green-500' },
    { name: 'JSON格式化', icon: Code, path: '/app/json-formatter', color: 'text-yellow-500' },
    { name: 'GitHub热门', icon: Github, path: '/app/github-trending', color: 'text-purple-500' },
  ];

  return (
    <div className="space-y-6">
      {/* Page header */}
      <div>
        <h1 className="text-3xl font-bold">仪表板</h1>
        <p className="text-muted-foreground">
          欢迎回来！{new Date().toLocaleDateString('zh-CN', { weekday: 'long' })}
        </p>
      </div>

      {/* System stats */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        {/* API 服务状态 */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">API 服务</CardTitle>
            <Server className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="flex items-center gap-2">
              {systemStats.apiStatus === 'checking' && (
                <>
                  <Loader2 className="h-4 w-4 animate-spin" />
                  <span className="text-sm">检查中...</span>
                </>
              )}
              {systemStats.apiStatus === 'online' && (
                <>
                  <CheckCircle2 className="h-4 w-4 text-green-500" />
                  <span className="text-2xl font-bold">运行中</span>
                </>
              )}
              {systemStats.apiStatus === 'offline' && (
                <>
                  <AlertCircle className="h-4 w-4 text-red-500" />
                  <span className="text-2xl font-bold">离线</span>
                </>
              )}
            </div>
            <p className="mt-1 text-xs text-muted-foreground">
              端口: 5001
            </p>
          </CardContent>
        </Card>

        {/* 待办事项 */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">待办事项</CardTitle>
            <CheckSquare className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {toolStats.todoCount - toolStats.todoCompleted}
            </div>
            <p className="text-xs text-muted-foreground">
              共 {toolStats.todoCount} 项，已完成 {toolStats.todoCompleted} 项
            </p>
          </CardContent>
        </Card>

        {/* 笔记统计 */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">笔记内容</CardTitle>
            <FileText className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {(toolStats.notesLength / 1024).toFixed(1)} KB
            </div>
            <p className="text-xs text-muted-foreground">
              {toolStats.notesLength} 个字符
            </p>
          </CardContent>
        </Card>

        {/* 存储使用 */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">本地存储</CardTitle>
            <Database className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{getStorageSize()} KB</div>
            <p className="text-xs text-muted-foreground">
              浏览器缓存数据
            </p>
          </CardContent>
        </Card>
      </div>

      {/* Quick access */}
      <Card>
        <CardHeader>
          <CardTitle>快速访问</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
            {quickAccessTools.map((tool) => {
              const Icon = tool.icon;
              return (
                <Link key={tool.name} to={tool.path}>
                  <Button
                    variant="outline"
                    className="h-auto w-full flex-col gap-2 p-4"
                  >
                    <Icon className={`h-8 w-8 ${tool.color}`} />
                    <span className="text-sm font-medium">{tool.name}</span>
                  </Button>
                </Link>
              );
            })}
          </div>
        </CardContent>
      </Card>

      <div className="grid gap-6 lg:grid-cols-2">
        {/* 工具状态 */}
        <Card>
          <CardHeader>
            <CardTitle>工具状态</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div className="flex items-center justify-between border-b pb-3">
                <div className="flex items-center gap-3">
                  <CheckSquare className="h-5 w-5 text-blue-500" />
                  <div>
                    <p className="font-medium">待办事项</p>
                    <p className="text-sm text-muted-foreground">
                      {toolStats.todoCount} 个任务
                    </p>
                  </div>
                </div>
                <Badge variant="secondary">
                  {toolStats.todoCompleted}/{toolStats.todoCount}
                </Badge>
              </div>

              <div className="flex items-center justify-between border-b pb-3">
                <div className="flex items-center gap-3">
                  <FileText className="h-5 w-5 text-green-500" />
                  <div>
                    <p className="font-medium">Markdown笔记</p>
                    <p className="text-sm text-muted-foreground">
                      {(toolStats.notesLength / 1024).toFixed(1)} KB
                    </p>
                  </div>
                </div>
                <Badge variant="secondary">活跃</Badge>
              </div>

              <div className="flex items-center justify-between border-b pb-3">
                <div className="flex items-center gap-3">
                  <Github className="h-5 w-5 text-purple-500" />
                  <div>
                    <p className="font-medium">GitHub热门</p>
                    <p className="text-sm text-muted-foreground">
                      {toolStats.githubCacheTime ? '已缓存' : '未缓存'}
                    </p>
                  </div>
                </div>
                <Badge variant={toolStats.githubCacheTime ? 'default' : 'secondary'}>
                  {toolStats.githubCacheTime ? '就绪' : '待用'}
                </Badge>
              </div>

              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <Bot className="h-5 w-5 text-orange-500" />
                  <div>
                    <p className="font-medium">Dify智能体</p>
                    <p className="text-sm text-muted-foreground">外部服务</p>
                  </div>
                </div>
                <Badge variant="secondary">iframe</Badge>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 系统信息 */}
        <Card>
          <CardHeader>
            <CardTitle>系统信息</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div className="flex items-center justify-between border-b pb-3">
                <div className="flex items-center gap-3">
                  <Activity className="h-5 w-5 text-blue-500" />
                  <div>
                    <p className="font-medium">系统版本</p>
                    <p className="text-sm text-muted-foreground">Feng Admin</p>
                  </div>
                </div>
                <Badge>v2.0</Badge>
              </div>

              <div className="flex items-center justify-between border-b pb-3">
                <div className="flex items-center gap-3">
                  <TrendingUp className="h-5 w-5 text-green-500" />
                  <div>
                    <p className="font-medium">可用工具</p>
                    <p className="text-sm text-muted-foreground">内置+外部</p>
                  </div>
                </div>
                <Badge>{systemStats.totalTools} 个</Badge>
              </div>

              <div className="flex items-center justify-between border-b pb-3">
                <div className="flex items-center gap-3">
                  <Clock className="h-5 w-5 text-yellow-500" />
                  <div>
                    <p className="font-medium">最后更新</p>
                    <p className="text-sm text-muted-foreground">
                      {systemStats.lastUpdate}
                    </p>
                  </div>
                </div>
                <Badge variant="outline">最新</Badge>
              </div>

              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <Calendar className="h-5 w-5 text-purple-500" />
                  <div>
                    <p className="font-medium">今天日期</p>
                    <p className="text-sm text-muted-foreground">
                      {new Date().toLocaleDateString('zh-CN')}
                    </p>
                  </div>
                </div>
                <Badge variant="secondary">
                  {new Date().toLocaleDateString('zh-CN', { weekday: 'short' })}
                </Badge>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* GitHub 缓存信息 */}
      {toolStats.githubCacheTime && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Github className="h-5 w-5" />
              GitHub 热门缓存
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-sm text-muted-foreground">
              最后更新时间: {toolStats.githubCacheTime}
            </p>
            <p className="mt-2 text-xs text-muted-foreground">
              缓存有效期为 4 小时，过期后会自动重新获取最新数据
            </p>
          </CardContent>
        </Card>
      )}
    </div>
  );
}

